import { Component, OnInit } from '@angular/core';
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import { Router, ActivatedRoute } from "@angular/router"; //路由引入

declare var $: any;
@Component({
	selector: 'sa-resource',
	templateUrl: './resource.component.html'
})
export class ResourceComponent implements OnInit {
	tableData = []; //table数据
	totalCount: number = 0; //分页总条数
	curPage: number = 1; //分页当前页
	pageSize: number = 10; //内置的分页每页条数
	searchKey: string = ''; //搜索keyword
	btnData: any = [];
	resourceAdd: boolean = false;
	resourceEdit: boolean = false;
	resourceDeleteBatch: boolean = false;
	resourceType: string = '';
	resourceTypeList: any = [{
		value: '0',
		label: '菜单'
	}, {
		value: '1',
		label: '按钮'
	}];
	constructor(private jsonApiService: JsonApiService, private router: Router, private activatedRoute: ActivatedRoute) {
		activatedRoute.queryParams.subscribe(queryParams => {
			this.curPage = queryParams.nowPage || 1;
		});
	}

	ngOnInit() {
		this.initBtn();
		this.load();
		System.import('assets/js/jquery.nestable.js').then(()=> {})
		// System.import('script-loader!smartadmin-plugins/bower_components/jquery-nestable/jquery.nestable.js').then(()=> {})
	}
	//table刷新
	refresh() {
		this.load();
	}
	//初始化权限按钮
	initBtn() {
		this.btnData = JSON.parse(decodeURIComponent(localStorage.getItem('cargpsw_system:resource')));
		if(!this.btnData) {
			return
		};
		for(let item of this.btnData) {
			if(item.sourceKey === "resource:add" && item.parentId) {
				this.resourceAdd = true;
			}
			if(item.sourceKey === "resource:edit" && item.parentId) {
				this.resourceEdit = true;
			}
			if(item.sourceKey === "resource:deleteBatch" && item.parentId) {
				this.resourceDeleteBatch = true;
			}
		}
	}
	//表格搜索
	table_search() {
		this.curPage = 1;
		this.searchKey = common.stringTrim(this.searchKey);
		this.load();
	}
	//初始化加载list数据
	load() {
		let data = {
			pageSize: this.pageSize,
			nowPage: this.curPage,
			parameters: {
				name: this.searchKey,
				type: this.resourceType
			}
		}
		let reqdata = 'gridPager=' + JSON.stringify(data);
		this.jsonApiService.http("resource/list.html", reqdata).subscribe(data => {
			this.tableData = data.exhibitDatas;
			this.totalCount = data.recordCount;
		})
	}
	//分页回调
	paginate(e) {
		this.curPage = e.page + 1;
		this.pageSize = e.rows;
		this.load();
	}
	//新建资源
	new_resource() {
		this.router.navigate(['/system/resource/resource-page'], {
			queryParams: {
				type: 'new'
			}
		});
	}
	//编辑资源页面
	updata_resource(row) {
		this.router.navigate(['/system/resource/resource-page'], {
			queryParams: {
				id: row.id,
				type: 'updata',
				nowPage: this.curPage
			}
		});
	}
	del_resource(row) {
		this.jsonApiService.confirm_message("此操作将永久删除数据,确认要删除?").then(() => {
			let reqdata = 'ids=' + row.id;
			this.jsonApiService.http("resource/deleteBatch.html", reqdata).subscribe(data => {
				this.jsonApiService.message(data.message);
				if(data.success) {
					this.load();
				}
			})
		})
	}

	//菜单排序
	menu_sort(modal){
		modal.show();
		this.showMenu();
	}

	//关闭菜单排序
	modalClose(modal){
		modal.hide();
		$("#nestableList").html("");
	}

	//确定菜单排序
	menuControlSubmit(modal){
		var setMenuList = $(".dd-handle");
		var menuListData = [];
		var that = this;
		// 确定框
		this.jsonApiService.confirm_message("此操作将永久调整顺序,确认是否修改?").then(() => {

			for (var i = 0; i < setMenuList.length; i++) {
				var menuList;
				var localParent = setMenuList[i].parentNode.parentNode;
				if (localParent.nodeName == 'OL') {
					// if (setMenuList[i].children.length == 0 && localParent.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.id == "nestableList") {
					// 	layer.alert("子层级最多到4级菜单");
					// 	return
					// }

					menuList = {
						"id": setMenuList[i].dataset.pcode,
						"indexNum": parseInt(setMenuList[i].dataset.order),
						"parentId": localParent.previousSibling.dataset.pcode,
					}

				} else {
					menuList = {
						"id": setMenuList[i].dataset.pcode,
						"indexNum": parseInt(setMenuList[i].dataset.order),
						"parentId": null,
					}
				}
				menuListData.push(menuList)
			}

			for (var j = 0; j < menuListData.length; j++) {
				menuListData[j].indexNum = j + 1;
			}

			that.jsonApiService.http_obj("resource/updateResourceTree.html", {"keys": JSON.stringify(menuListData)}).subscribe(data => {
				// that.jsonApiService.message(data.message);
				if(data.success) {
					that.modalClose(modal);
					that.confirmButton();
				}
			})

		}, function () {
		});
	}
	//确定是否重新排序
	confirmButton() {
		layer.confirm('确定现在看到菜单操作顺序结果，此次操作将回到登录页面', {
			btn: ['立即查看','下次再说'] //按钮
		  }, function(){
			localStorage.clear();
			window.location.reload();
		  });
		// this.jsonApiService.confirm_message("确定现在看到菜单操作顺序结果，此次操作将回到登录页面").then(() => {
		// 	localStorage.clear();
		// 	window.location.reload();
		// }, function () {
		// })
	}
	showMenu() {
		$("#nestableList").html("");
		var _htmlUIMenuList;
		// //请求全部表单的接口
		this.jsonApiService.http("resource/resourceTree.html", {}).subscribe(data => {
			// this.jsonApiService.message(data.message);
			if(data.success) {
				var resoureData = data.data;
				for (let i = 0; i < resoureData.length; i++) {
					let order = resoureData[i].indexNum == null ? i+1 : resoureData[i].indexNum
					if (resoureData[i].children.length > 0) {
						_htmlUIMenuList = '<li class="dd-item" data-pcode="' 
											+ resoureData[i].id + '"><button data-action="collapse" type="button">Collapse</button><button data-action="expand" type="button" style="display: none;">Expand</button><div class="dd-handle" data-pcode="' 
											+ resoureData[i].id + '" data-order="' 
											+ order + '" data-parentid="' 
											+ resoureData[i].parentId + '"> ' 
											+ resoureData[i].name + ' <span style="display:' 
											+ (!resoureData[i].isHide ? "none" : "inline-block") + ';float: right;color: gray;"><i class="fa fa-exclamation-circle" style="color:#ffb44b"></i>该模块不开放</span></div><ol id="' 
											+ resoureData[i].id + '" class="dd-list"></ol></li>';
						$("#nestableList").append(_htmlUIMenuList);

						this.menuDataHtml(resoureData[i])
					} else {
						_htmlUIMenuList = '<li class="dd-item" data-pcode="' + resoureData[i].id + '"><div class="dd-handle" data-pcode="' + resoureData[i].id + '" data-order="' + order + '" data-parentid="' + resoureData[i].parentId + '"> ' + resoureData[i].name + '<span style="display:' + (!resoureData[i].isHide ? "none" : "inline-block") + ';float: right;color: gray;"><i class="fa fa-exclamation-circle" style="color:#ffb44b"></i>  该模块不开放</span></div></li>';
						$("#nestableList").append(_htmlUIMenuList);
					}
				}
			}
		})
		$('#nestable').nestable({
			maxDepth: 2,
			scroll: true,
			scrollSensitivity: 1,
		});
	}


	menuDataHtml(data) {
		var _htmlUIMenu;
		for (let j = 0; j < data.children.length; j++) {
			let order = data.children[j].indexNum == null ? j+1 : data.children[j].indexNum
			if (data.children[j].children.length > 0) {
				_htmlUIMenu = '<li class="dd-item" data-pcode="' + data.children[j].id + '"><button data-action="collapse" type="button">Collapse</button><button data-action="expand" type="button" style="display: none;">Expand</button><div class="dd-handle" data-pcode="' + data.children[j].id + '" data-order="' + order + '" data-parentid="' + data.children[j].parentId + '"> ' + data.children[j].name + '<span style="display:' + (!data.children[j].isHide ? "none" : "inline-block") + ';float: right;color: gray;"><i class="fa fa-exclamation-circle" style="color:#ffb44b"></i>  该模块不开放</span></div><ol id="' + data.children[j].id + '" class="dd-list"></ol></li>';
				$("#" + data.id).append(_htmlUIMenu)

				this.menuDataHtml(data.children[j])
			} else {
				_htmlUIMenu = '<li class="dd-item" data-pcode="' + data.children[j].id + '"><div class="dd-handle" data-pcode="' + data.children[j].id + '" data-order="' + order + '" data-parentid="' + data.children[j].parentId + '"> ' + data.children[j].name + '<span style="display:' + (!data.children[j].isHide ? "none" : "inline-block") + ';float: right;color: gray;"><i class="fa fa-exclamation-circle" style="color:#ffb44b"></i>  该模块不开放</span></div></li>';
				$("#" + data.id).append(_htmlUIMenu)
			}
		}
	}
}